<?php

namespace app\admin\controller\course;

use app\common\controller\Backend;
use app\common\library\MyDateTime;
use fast\Tree;
/**
 * 
 *
 * @icon fa fa-file
 */
class Course extends Backend
{
    
    /**
     * Course模型对象
     */
    protected $model = null;
    protected $noNeedRight=["lists","status","auto"];
    protected $noNeedLogin=["lists","status","auto"];


    public function _initialize()
    {
        parent::_initialize();
        $this->shopid=false;
        $this->model = model('Course');
        $this->modelValidate = true;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where);
            $total = $total->where("status", "<>", -1);
            //if ($_SESSION['think']['admin']['group_id'] == 2) {
            //    $total = $total->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            //}
            $total = $total
                ->count();

            $list = $this->model
                ->where($where);
            //if ($_SESSION['think']['admin']['group_id'] == 2) {
            //    $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            //}
            $list = $list->where("status", "<>", -1)
                ->order('weigh desc,id desc')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            //$this->model->getLastSql();
            $list = collection($list)->toArray();

//            $tree = Tree::instance();
//            $tree->init($list, 'pid');
//            $list = $tree->getTreeList($tree->getTreeArray(0), 'name');
//            $data = array();
//            for ($i = 0; $i < count($list); $i++) {
//                $v = $list[$i];
//                $data[] = [
//                    'id' => $v['id'],
//                    'parent' => $v['pid'] ? $v['pid'] : '#',
//                    'name' => $v['name'],
//                    'type' => $v['type'],
//                    'status' => $v['status'],
//                    'school_id' => model("School")->getSchool_idTextAttr($v['school_id'])
//                ];
//            }


            for($i=0;$i<count($list);$i++){
//                $list[$i]['province_id']=model('Cityarea')->getProvince_idTextAttr($list[$i]['province_id']);
//                $list[$i]['city_id']=model('Cityarea')->getCity_idTextAttr($list[$i]['city_id']);
//                $list[$i]['district_id']=model('Cityarea')->getDistrict_idTextAttr($list[$i]['district_id']);
//                $list[$i]['province_id']=preg_replace("/\/$/","",model('Cityarea')->getProvince_idTextAttr($list[$i]['province_id'])."/".$list[$i]['city_id']."/".$list[$i]['district_id']);
//                $list[$i]['school_id']=model('School')->getSchool_idTextAttr($list[$i]['school_id'],$list[$i]);
                //$v['course_type']=$this->model->getCourse_typeTextAttr($v['course_type'],$v);
                $list[$i]['course_type']=$this->model->getCourse_typeTextAttr($list[$i]['course_type'],$list[$i]);
                //$v['is_post']=$this->model->getIs_postTextAttr($v['is_post'],$v);
                $list[$i]['is_post']=$this->model->getIs_postTextAttr($list[$i]['is_post'],$list[$i]);
//                $list[$i]['sqstr']=$this->model->getSqstrTextAttr($list[$i]['sqstr'],$list[$i]);
                //$v['class_type']=$this->model->getClass_typeTextAttr($v['class_type'],$v);
                $list[$i]['class_type']=$this->model->getClass_typeTextAttr($list[$i]['class_type'],$list[$i]);
                $list[$i]['subject_lv']=$this->model->getSubject_lvTextAttr($list[$i]['subject_lv'],$list[$i]);
                //$v['ocation_id']=$this->model->getOcation_idTextAttr($v['ocation_id'],$v);
                $list[$i]['ocation_id']=model("Ocation")->getOcation_idTextAttr($list[$i]['ocation_id'],$list[$i]);
                $list[$i]['classes_id']=model("Classes")->getClasses_idTextAttr($list[$i]['classes_id'],$list[$i]);
                $list[$i]['address_lv']=$this->model->getAddress_lvTextAttr($list[$i]['address_lv'],$list[$i]);
                //$v['skip_holiday']=$this->model->getSkip_holidayTextAttr($v['skip_holiday'],$v);
                $list[$i]['skip_holiday']=$this->model->getSkip_holidayTextAttr($list[$i]['skip_holiday'],$list[$i]);
//                $list[$i]['teacherstr']=$this->model->getTeacherstrTextAttr($list[$i]['teacherstr'],$list[$i]);
                $list[$i]['teacher_id']=$this->model->getTeacher_idTextAttr($list[$i]['teacher_id'],$list[$i]);
                $list[$i]['manager_id']=$this->model->getManager_idTextAttr($list[$i]['manager_id'],$list[$i]);
                //$v['community_id']=$this->model->getCommunity_idTextAttr($v['community_id'],$v);
                $list[$i]['community_id']=$this->model->getCommunity_idTextAttr($list[$i]['community_id'],$list[$i]);
                //$v['rel_type']=$this->model->getRel_typeTextAttr($v['rel_type'],$v);
                $list[$i]['rel_type']=$this->model->getRel_typeTextAttr($list[$i]['rel_type'],$list[$i]);
                //$v['rel_id']=$this->model->getRel_idTextAttr($v['rel_id'],$v);
                $list[$i]['rel_id']=$this->model->getRel_idTextAttr($list[$i]['rel_id'],$list[$i]);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
//        $this->assignconfig("relType",$_REQUEST['relType']);
//        $this->assignconfig("relId",$_REQUEST['relId']);
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        //$this->model->validate($validate);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['check_time']=str2time($params['check_time']);
                    $params['course_end']=str2time($params['course_end']);
                    $params['course_start']=str2time($params['course_start']);
                    $params['after_time']=str2time($params['after_time']);
                    $params['evaluation_time']=str2time($params['evaluation_time']);
                    $params['reminder_time']=str2time($params['reminder_time']);
                    $params['create_time']=$datatime;
                    $params['teacher_id']=0;
                    $params['manager_id']=0;
                    unset($params['delete_time']);
                    unset($params['update_time']);
//                    if($_SESSION['think']['admin']['group_id']==2){
//                        $params['city_id']=$_SESSION['think']['admin']['city_id'];
//                    }
                    $params['ckrqsxtj_date_begin']=(!array_key_exists("ckrqsxtj_date_begin",$params)||$params['ckrqsxtj_date_begin']=="")?date("Y-m-d",time()):date("Y-m-d",strtotime($params['ckrqsxtj_date_begin']));
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //$this->assign('user_type', $_SESSION['think']['admin']['group_id']);
        $check_time=time();
        $this->view->assign("check_time", $check_time);
        $course_end=time();
        $this->view->assign("course_end", $course_end);
        $course_start=time();
        $this->view->assign("course_start", $course_start);
        $after_time=time();
        $this->view->assign("after_time", $after_time);
        $evaluation_time=time();
        $this->view->assign("evaluation_time", $evaluation_time);
        $reminder_time=time();
        $this->view->assign("reminder_time", $reminder_time);
        $this->assign("admin",$_SESSION['think']['admin']);
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        //$row->validate($validate);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['check_time']=str2time($params['check_time']);
                    $params['course_end']=str2time($params['course_end']);
                    $params['course_start']=str2time($params['course_start']);
                    $params['after_time']=str2time($params['after_time']);
                    $params['evaluation_time']=str2time($params['evaluation_time']);
                    $params['reminder_time']=str2time($params['reminder_time']);
                    $params['update_time']=$datatime;
                    unset($params['delete_time']);
                    unset($params['create_time']);
//                    if($_SESSION['think']['admin']['group_id']==2){
//                        $params['city_id']=$_SESSION['think']['admin']['city_id'];
//                    }
                    $params['ckrqsxtj_date_begin']=(!array_key_exists("ckrqsxtj_date_begin",$params)||$params['ckrqsxtj_date_begin']=="")?date("Y-m-d",time()):date("Y-m-d",strtotime($params['ckrqsxtj_date_begin']));
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row['check_time']=int2date($row['check_time']);
        $row['course_end']=int2date($row['course_end']);
        $row['course_start']=int2date($row['course_start']);
        $row['after_time']=int2date($row['after_time']);
        $row['evaluation_time']=int2date($row['evaluation_time']);
        $row['reminder_time']=int2date($row['reminder_time']);
        $this->view->assign("row", $row);
        $this->assign("admin",$_SESSION['think']['admin']);
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        return $this->view->fetch();

    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row=$this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL){
        $where="where 1=1";
        if($_SESSION['think']['admin']['group_id']!=1){
            $where.=" and city_id='{$_SESSION['think']['admin']['city_id']}'";
        }
        $page=1;
        $pagesize=50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn=preg_split("/\,/",$keyValue);
                    for($i=0;$i<count($nn);$i++) {
                        $where.= " and $keyField='{$nn[$i]}'";
                    }
                }
            }else{
                $where="where 1=1";
                if(isset($_REQUEST['city_id'])&&$_REQUEST['city_id']>0){
                    //$where.=" and city_id=".$_REQUEST['city_id'];
                }
            }
        }
        $sql="select id,title name from dev002_gxyusheng.course $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

//        $r_name = model("School")->field("id,name")->where("id", "=", $_REQUEST['school_id'])->select();
//        if (empty($list)&&!empty($r_name)) {
//            $data = array(
//                "type" => "file",
//                "pid" => 0,
//                "name" => $r_name[0]['name']."学科",
//                "title" => $r_name[0]['name'],
//                "ismenu" => 0,
//                "createtime" => time(),
//                "updatetime" => time(),
//                "status" => 1,
//                "school_id" => $_REQUEST['school_id'],
//            );
//            $this->model->create($data);
//        }
//        $sql="select id,pid,name,title,status from dev002_gxyusheng.course $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
//        $list = db()->query($sql);
//        $tree = Tree::instance();
//        $tree->init($list, 'pid');
//        $list = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.course $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

    public function changeStatus($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

    public function auto($ids = '')
    {
        global $dayDMap,$dayXMap;
// 课程类型
        $subjects = ["声乐课", "舞蹈课", "书法课"];
        $subjects =ids2array("subjects");
// 每门课要上的课时数
        $hour = 30;
        $hour = $_REQUEST['hour'];
// 可用班级
        $locations = ["舞蹈班1", "舞蹈班2", "舞蹈班3","声乐课1"];
        $locations =ids2array("classes");

        $dayDMap = [
            '一' => 1,
            '二' => 2,
            '三' => 3,
            '四' => 4,
            '五' => 5,
            '六' => 6,
            '日' => 7
        ];

        $dayXMap = [
            1 => '一',
            2 => '二',
            3 => '三',
            4 => '四',
            5 => '五',
            6 => '六',
            7 => '日'
        ];

        // 上课时间段
        function findN($classDays) {
            global $dayDMap;
            $days = explode('、', str_replace('每周', '', $classDays));
            $result=[];
            for($i=0;$i<count($days);$i++){
                $result[]=$dayDMap[trim($days[$i])];
            }
            return $result;
        }

        $sksjd = trim($_REQUEST["sksjd"]);
        preg_match_all("/^(每周.*)([0-9]{1,2}\:[0-9]{1,2}(?:\-|\:)[0-9]{1,2}\:[0-9]{1,2})$/Uimx",$sksjd,$nn);
        $weeklines=array();
        $classDaysarr=array();
        for($i=0;$i<count($nn[1]);$i++){
            $lines=array();
            $lines["n"]=findN($nn[1][$i]);
            $classDaysarr=array_merge($lines["n"],$classDaysarr);
            $lines["classDays"]=$nn[1][$i];
            $lines["classTime"]=$nn[2][$i];
            $weeklines[]=$lines;
        }
        sort($classDaysarr);
        $result = [];
        for ($i = 0; $i < count($classDaysarr); $i++) {
            $result[] = $dayXMap[trim($classDaysarr[$i])];
        }
        $classDaysarrALL="每周".join("、",$result);
        function getDayClassTimes($currentDate,$weeklines){
            $dayOfWeek = (int) $currentDate->format('N');
            $result=array();
            for($i=0;$i<count($weeklines);$i++){
                if(in_array($dayOfWeek,$weeklines[$i]['n'])){
                    $result[]=$weeklines[$i];
                }
            }
            return $result;
        }

// 开始日期
        $startDate = "2025-02-17";
        $startDate = $_REQUEST["ckrqsxtj_date_begin"];
// 教室使用期限
        $locations_tj = [
            ["教室1", "2025-01-14", "2025-03-06"],
            ["教室2", "2025-01-14", "2025-05-06"],
            ["教室3", "2025-01-14", "2025-06-06"]
        ];
        $locations_tj =ids2localtionsLimit("classes");


// 最终的课程安排时间表
        $schedule = [];


        function week($n){
            global $dayXMap;
            $n=trim($n);
            return $dayXMap[$n];
        }

// 函数：计算下一个上课日期
        function nextClassDate(MyDateTime $currentDate, $classDays) {
            global $dayDMap;
            $dayOfWeek = (int) $currentDate->format('N');
            $days = explode('、', str_replace('每周', '', $classDays));
            $foundNextDay = false;
            $nextDay = null;
            while (!$foundNextDay) {
                $currentDate->modify('+1 day');
                $currentDayOfWeek = (int) $currentDate->format('N');
                $dayName = array_search($currentDayOfWeek, $dayDMap);
                if (in_array($dayName, $days)) {
                    $foundNextDay = true;
                    $nextDay = $currentDate;
                }
            }
            return $nextDay;
        }


// 预先指定课程和教室的映射
        $predefinedSubjectLocations = [
            "声乐课" => "教室1、教室3",
            "舞蹈课" => "教室2"
        ];


// 为每门课程分配一个教室
        $subjectLocations = [];
        foreach ($subjects as $subject) {
            if (isset($predefinedSubjectLocations[$subject])) {
                $subjectLocations[$subject] = $predefinedSubjectLocations[$subject];
            } else {
                // 自动分配教室
                $subjectLocations[$subject] = $locations[count($subjectLocations) % count($locations)];
            }
        }


// 为每门课程生成课程安排
        $count=0;
        $location_histroys=array();
        foreach ($subjects as $subject) {
            // 初始化当前课程的开始日期
            $currentDate = new MyDateTime($startDate);
            $classCount = 0;
            // 获取该课程对应的教室
            $location = $subjectLocations[$subject];
            $locationInfo = null;
            foreach ($locations_tj as $tj) {
                if ($tj[0] == $location) {
                    $locationInfo = $tj;
                    break;
                }
            }
            $locationStart = new MyDateTime($locationInfo[1]);
            $locationEnd = new MyDateTime($locationInfo[2]);
            while ($classCount < $hour) {
                $currentDayClassTimes=getDayClassTimes($currentDate,$weeklines);
                for($c=0;$c<count($currentDayClassTimes);$c++) {
                    $classTime=$currentDayClassTimes[$c]["classTime"];
                    $classDays=$currentDayClassTimes[$c]["classDays"];
                    $sj = $currentDate->format('Y-m-d') . " " . $classTime;
                    $sjstart=date("Y-m-d H:i:s",strtotime(preg_replace("/\-[0-9]{1,2}\:.*$/","",$sj)));
                    $startsjDate=new MyDateTime($sjstart);
                    if ($currentDate->getTimestamp() >= $locationStart->getTimestamp() && $currentDate->getTimestamp() <= $locationEnd->getTimestamp()) {
                        if (!in_location_histroys($sj, $location, $location_histroys)) {
                            $da = array();
                            $da['location'] = $location;
                            $da['sj'] = $sj;
                            $location_histroys[] = $da;
                            $schedule[] = [
                                "课程" => $subject,
                                "班级" => $location,
                                "时间" => $sj, // 组合日期和时间
                                "周几" => week($currentDate->format('N')),
                                "时间戳" => $startsjDate->getTimestamp() // 新增时间戳，用于排序
                            ];
                            $classCount++;
                            $count++;
                        }
                    } else {
                         $schedule[] = [
                            "课程" => $subject,
                            "班级" => "(<span style='color:red'>无教室</span>,{$location}到期)",
                            "时间" => $sj, // 组合日期和时间
                            "周几" => week($currentDate->format('N')),
                            "时间戳" => $startsjDate->getTimestamp(), // 新增时间戳，用于排序
                        ];
                        $classCount++;
                        $count++;
                    }
                }
                $currentDate = nextClassDate($currentDate,$classDaysarrALL);
            }
        }


// 对课程安排按时间戳排序
        usort($schedule, function($a, $b) {
            if ($a["时间戳"] == $b["时间戳"]) {
                return strcmp($a["课程"], $b["课程"]);
            }
            return $a["时间戳"] <=> $b["时间戳"];
        });

        if(isset($_REQUEST["real"])&&$_REQUEST["real"]==1){
            $params = $this->request->post("row/a");
            $courseData=array();
            $courseData["rel_type"]=$params["rel_type"];
            $courseData["rel_id"]=$params["rel_id"];
            $courseData["title"]=$params["title"];
            $courseData["course_cover"]=$params["course_cover"];
            $courseData["intro"]=$params["intro"];
            $courseData["course_type"]=$params["course_type"];
            $courseData["status"]=$params["status"];
            $courseData["is_post"]=$params["is_post"];
//            $courseData["class_type"]=$params["class_type"];
            if($params["subject_lv"]){
                $courseData["subject_lv"]=$params["subject_lv"];
            }
            $courseData["school_id"]=$params["school_id"];
            $courseData["community_id"]=$params["community_id"];
            if($params["address_lv"]) {
                $courseData["address_lv"] = $params["address_lv"];
            }
            $courseData["classes_id"]=$params["classes_id"];
            $courseData["hour"]=$params["hour"];
            $courseData["ckrqsxtj_date_begin"]=$params["ckrqsxtj_date_begin"];
//            $courseData["ckrqsxtj_date_end"]=$params["ckrqsxtj_date_end"];
            if($_SESSION['think']['admin']['group_id']==3){
                $r=model("School")->where("id","=",$_SESSION['think']['admin']['school_id'])->select();
            }elseif($_SESSION['think']['admin']['group_id']==8){
                $r=model("Community")->where("id","=",$_SESSION['think']['admin']['Community_id'])->select();
            }
            $courseData["province_id"]=$r[0]['province_id'];
            $courseData["city_id"]=$r[0]["city_id"];
            $courseData["district"]=$r[0]["district_id"];
            //$courseData["sign_before"]=$params["sign_before"];
            //$courseData["end_date"]=$params["end_date"];
            //$courseData["sign_before"]=$params["sign_before"];
            //$courseData["sign_after"]=$params["sign_after"];
            //$courseData["close_after"]=$params["close_after"];
            //$courseData["evaluate_after"]=$params["evaluate_after"];
            //$courseData["check_time"]=$params["check_time"];
            $courseData["longitude"]=$params["longitude"];
            $courseData["latitude"]=$params["latitude"];
            $courseData["amount"]=$params["amount"];
            $courseData["menber_limit"]=$params["menber_limit"];
            $courseData["is_open"]=$params["is_open"];
            $courseData["reminder"]=$params["reminder"];
            $courseData["reminder_content"]=$params["reminder_content"];
            $courseData["reminder_user"]=$params["reminder_user"];
            //$courseData["reminder_time"]=$params["reminder_time"];
            $courseData["create_time"]=date("Y-m-d H:i:s");

            $course_id = model("Course")->insertUpdate($courseData,["title","school_id","community_id"]);
            foreach ($schedule as $class) {
                $courseData=array();
                $courseData["course_id"]=$course_id;
                $courseData["event_time"]=$class["时间"];
                $courseData["week"]=$class["周几"];
                $r=model("Subjectlv")->where("name","=",$class["课程"])->select();
                if($r){
                    $courseData["subjectlv_id"]=$r[0]['id'];
                }else{
                    $courseData["subjectlv_id"]=0;
                }
                $r=model("Classes")->where("name","=",$class["班级"])->select();
                if($r){
                    $courseData["classes_id"]=$r[0]['id'];
                }else{
                    $courseData["classes_id"]=0;
                }
                $courseData["createtime"]=date("Y-m-d H:i:s");
                model("Courseevent")->insertUpdate($courseData,["course_id","event_time","classes_id"]);
            }
            $result = array(
                "code" => 1,
                "data" => [],
                "msg" => "正式生成了{$count}条记录",
                "count" => $count
            );
            echo json_encode($result);
            exit;
        }else {
// 输出课程安排时间表
            $text = "";
            $text .= "<table border='1'>";
            $text .= "<tr><th style='width:200px;text-align:center'>时间</th><th style='width:20px;text-align:center'>周几</th><th style='width:100px;text-align:center'>课程</th><th style='width:400px;text-align:center'>教室</th></tr>";
            foreach ($schedule as $class) {
                $text .= "<tr>";
                $text .= "<td style='width:200px;text-align:center'>" . $class["时间"] . "</td>";
                $text .= "<td style='width:50px;text-align:center'>" . $class["周几"] . "</td>";
                $text .= "<td style='width:100px;text-align:center'>" . $class["课程"] . "</td>";
                $text .= "<td style='width:400px;text-align:left;padding-left:5px'>" . $class["班级"] . "</td>";
                $text .= "</tr>";
            }
            $text .= "</table>";
            $result = array(
                "code" => 1,
                "data" => $text,
                "msg" => "生成了{$count}条记录",
                "count" => $count
            );
            echo json_encode($result);
            exit;
        }
    }

}
